/*
 * Copyright (C) 2023, KylinSoft Co., Ltd.
 *
 *  This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * Authors: iaom <zhangpengfei@kylinos.cn>
 */

#include "notification-global-settings.h"
#include <QJsonObject>
#include <QQmlEngine>
#include <QDBusInterface>
#include <QDBusReply>
#include <QDBusMessage>
#include <QDebug>
#include "settings-manager.h"
#include "settings-properties.h"
#include "settings-properties-info.h"

namespace UkuiNotification{
class NotificationGlobalSettingsPrivate
{
    friend class NotificationGlobalSettings;
private:
    QJsonObject m_settings;
    QDBusInterface *m_usdInterface = nullptr;
    int m_currentScreenMode = 0; //0-仅主屏；1-镜像；2-扩展；3-仅副屏
};
}

using namespace UkuiNotification;// UkuiNotification

NotificationGlobalSettings::NotificationGlobalSettings(QObject *parent) : QObject(parent), d(new NotificationGlobalSettingsPrivate())
{
    qmlRegisterUncreatableType<UkuiNotification::NotificationGlobalSettings>("org.ukui.notification.client", 1, 0, "NotificationGlobalSettings", "");
    connect(SettingsManager::self(), &SettingsManager::settingsDataChanged, this, &NotificationGlobalSettings::settingsDataChanged);
    d->m_settings = SettingsManager::self()->getGlobalSettings();
    d->m_usdInterface = new QDBusInterface("org.ukui.SettingsDaemon",
                                           "/org/ukui/SettingsDaemon/xrandr",
                                           "org.ukui.SettingsDaemon.xrandr");
    if(!d->m_usdInterface->isValid()) {
        qWarning() << "NotificationGlobalSettings: Fail to creat org.ukui.SettingsDaemon dbus interface!";
        return;
    }
    QDBusReply<int> reply = d->m_usdInterface->call("getScreenMode", "ukui-notification-server");
    if (reply.isValid()) {
        d->m_currentScreenMode = reply.value();
    } else {
        qWarning()<<"NotificationGlobalSettings: Call getScreenMode failed!";
    }
    connect(d->m_usdInterface, SIGNAL(screenModeChanged(int)), this, SLOT(screenModeChanged(int)));
}

NotificationGlobalSettings::~NotificationGlobalSettings()
{
    if(d) {
        delete d;
        d = nullptr;
    }
}

bool NotificationGlobalSettings::scheduleTurnOnDND()
{
    return d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::ScheduleTurnOnDND).name()).toVariant().toBool();
}

QTime NotificationGlobalSettings::scheduleTurnOnDNDTime()
{
    return QTime::fromString(d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::ScheduleTurnOnDNDTime).name()).toString(), "HHmm");
}

QTime NotificationGlobalSettings::scheduleTurnOffDNDTime()
{
    return QTime::fromString(d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::ScheduleTurnOffDNDTime).name()).toString(), "HHmm");
}

bool NotificationGlobalSettings::DNDWhileMultiScreen()
{
    return d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::DNDWhileMultiScreen).name()).toVariant().toBool();
}

bool NotificationGlobalSettings::DNDWhileFullScreen()
{
    return d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::DNDWhileFullScreen).name()).toVariant().toBool();
}

bool NotificationGlobalSettings::notifyAlarmWhileDND()
{
    return d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::NotifyAlarmWhileDND).name()).toVariant().toBool();
}

bool NotificationGlobalSettings::receiveNotificationsFromApps()
{
    return d->m_settings.value(SettingsPropertiesInfo(SettingsProperty::ReceiveNotificationsFromApps).name()).toVariant().toBool();
}

void NotificationGlobalSettings::settingsDataChanged()
{
    QJsonObject data = SettingsManager::self()->getGlobalSettings();
    for(SettingsProperty::Property property : GLOBAL_SETTINGS) {
        QString name = SettingsPropertiesInfo(property).name();
        QJsonValue value = data.value(name);
        if(d->m_settings.value(name) != value) {
            d->m_settings.insert(name, value);
            switch (property) {
                case SettingsProperty::ScheduleTurnOnDND:
                    Q_EMIT scheduleTurnOnDNDChanged(value.toVariant().toBool());
                    break;
                case SettingsProperty::ScheduleTurnOnDNDTime:
                    Q_EMIT scheduleTurnOnDNDTimeChanged(QTime::fromString(value.toString(), "HHmm"));
                    break;
                case SettingsProperty::ScheduleTurnOffDNDTime:
                    Q_EMIT scheduleTurnOffDNDTimeChanged(QTime::fromString(value.toString(), "HHmm"));
                    break;
                case SettingsProperty::DNDWhileMultiScreen:
                    Q_EMIT DNDWhileMultiScreenChanged(value.toVariant().toBool());
                    break;
                case SettingsProperty::DNDWhileFullScreen:
                    Q_EMIT DNDWhileFullScreenChanged(value.toVariant().toBool());
                    break;
                case SettingsProperty::NotifyAlarmWhileDND:
                    Q_EMIT notifyAlarmWhileDNDChanged(value.toVariant().toBool());
                    break;
                case SettingsProperty::ReceiveNotificationsFromApps:
                    Q_EMIT receiveNotificationsFromAppsChanged(value.toVariant().toBool());
                    break;
                default:
                    break;
            }
        }
    }
}

void NotificationGlobalSettings::setScheduleTurnOnDND(bool enable)
{
    SettingsManager::self()->setGlobalSettings(SettingsProperty::ScheduleTurnOnDND, enable);
}

void NotificationGlobalSettings::setScheduleTurnOnDNDTime(const QTime &time)
{
    SettingsManager::self()->setGlobalSettings(SettingsProperty::ScheduleTurnOnDNDTime, time);
}

void NotificationGlobalSettings::setScheduleTurnOffDNDTime(const QTime &time)
{
    SettingsManager::self()->setGlobalSettings(SettingsProperty::ScheduleTurnOffDNDTime, time);
}

void NotificationGlobalSettings::setDNDWhileMultiScreen(bool enable)
{
    SettingsManager::self()->setGlobalSettings(SettingsProperty::DNDWhileMultiScreen, enable);
}

void NotificationGlobalSettings::setDNDWhileFullScreen(bool enable)
{
    SettingsManager::self()->setGlobalSettings(SettingsProperty::DNDWhileFullScreen, enable);
}

void NotificationGlobalSettings::setNotifyAlarmWhileDND(bool enable)
{
    SettingsManager::self()->setGlobalSettings(SettingsProperty::NotifyAlarmWhileDND, enable);
}

void NotificationGlobalSettings::setReceiveNotificationsFromApps(bool enable)
{
    SettingsManager::self()->setGlobalSettings(SettingsProperty::ReceiveNotificationsFromApps, enable);
}

bool NotificationGlobalSettings::isDND() {
    bool dnd = false;
    if(scheduleTurnOnDND()) {
        QTime currentTime = QTime::currentTime();
        if( currentTime >= scheduleTurnOnDNDTime() && currentTime < scheduleTurnOffDNDTime()) {
            dnd = true;
        }
    }
    if(!dnd) {
        if(DNDWhileMultiScreen()) {
            if(d->m_currentScreenMode == 1 || d->m_currentScreenMode == 2) {
                dnd = true;
            }
        }
    }
    if(!dnd) {
        if(DNDWhileFullScreen()) {
            QDBusMessage msg = QDBusMessage::createMethodCall(QStringLiteral("org.kde.KWin"),
                                                              QStringLiteral("/KWin"),
                                                              QStringLiteral("org.kde.KWin"),
                                                              QStringLiteral("haveFullScreenActiveWindow"));
            QDBusReply<bool> reply  = QDBusConnection::sessionBus().call(msg);
            if(reply.isValid()) {
                dnd = reply.value();
            }
        }
    }
    return dnd;
}

void NotificationGlobalSettings::screenModeChanged(int mode) {
    d->m_currentScreenMode = mode;
}

